<template>
  <!-- 总部团队管理 -->
  <div class="teams-manage">
    <div class="auth-title" v-if="waitAuthList.length">待审核</div>
    <div class="top-cell" v-for="(item, index) in waitAuthList" :key="index + 'a'">
      <div class="avatar-wrapper">
        <img src="@/assets/image/default-avatar.jpeg" alt=""/>
      </div>
      <div class="top-center">
        <p class="names">
          <!-- <span class="real-name">{{ item.real_name }}</span> -->
          <span class="shop-name">{{ item.real_name }}</span>
        </p>
        <p class="shop-name">手机号：{{ item.mobile }}</p>
      </div>
      <p class="auth-btn" @click="jumpAuth('/inviteAuth', item)">去审核</p>
    </div>

    <div class="invite-cell">
      <p>当前账号数量：<span class="green-text">
        {{ role === 'HQ' ? allList.length : memberList.length }}个
      </span></p>
      <p class="invite-btn" @click="inviteMerchant">
        {{ (role === 'HQ' || role === 'MERCHANT') ? '邀请新成员' : '开通子账号'}}
      </p>
    </div>

    <div class="group-list">
      <div 
        class="group-item" 
        v-for="(item, index) in groupList" 
        :key="index">
        <div class="group-label-cell">
          <div class="group-name">{{ item.groupName }}</div>
          <img
            v-if="item.isFold"
            @click="toggleGroup(index)"
            src="@/assets/image/group-down.png" alt="" />
          <img
            v-else
            @click="toggleGroup(index)"
            src="@/assets/image/group-up.png" alt="" />
        </div>
        <div class="shop-list" v-if="!item.isFold">
          <div 
            class="shop-item" 
            v-for="(shop, shopIndex) in item.shopList" 
            :key="shopIndex">
            <div class="avatar-wrapper">
              <img :src="shop.head_image" alt="" v-if="shop.head_image"/>
              <img src="@/assets/image/default-avatar.jpeg" alt="" v-else/>
            </div>
            <p class="shop-item-name">{{ shop.remark || shop.username }}</p>
            <p class="view" @click="jumpDetail(shop)">查看门店</p>
          </div>
        </div>
      </div>
    </div>

    <div class="top-cell" v-for="(item, index) in memberList" :key="index + 'b'">
      <div class="avatar-wrapper">
        <img :src="item.head_image" alt="" v-if="item.head_image"/>
        <img src="@/assets/image/default-avatar.jpeg" alt="" v-else/>
      </div>
      <div class="top-center">
        <p class="names">
          <span class="real-name">{{ item.username }}</span>
          <!-- <span class="shop-name">{{ item.username }}</span> -->
        </p>
        <p class="shop-name">手机号：{{ item.mobile }}</p>
      </div>
      <p class="view" @click="viewAccount(item)">查看账号</p>
    </div>

    <!-- 邀请新成员弹窗 -->
    <van-popup v-model="showDialog">
      <div class="popup-content">
        <div class="dialog-title">邀请{{ nextRoleType }}</div>
        <div class="dialog-sub-title">
          截图保存二维码，微信转发给新成员申请加入。
          <span v-if="role=='OPERATE'" class="yellow-text">剩余可开通{{ 30 - memberList.length}}个子账号</span>
        </div>
        <div class="qr" style="margin-top:20px" id="qrcode"></div>
        <!-- <img :src="qrImageUrl" alt="" id="qrcode" style="margin-top:20px" class="qr"/> -->
        <!-- <img src="@/assets/image/qr-code.png" alt="" class="qr"/> -->
        <div class="know-btn" @click="showDialog = false">我知道了</div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { 
  listMerchant, listWaitAuthMerchant,
  getWaitAuthMember, inviteMerchant, listMembers } from '@/api/account'
import QRCode from 'qrcodejs2-fix'
import { selfTeamManage } from '@/api/selfuse'
import { getOssDomain } from '@/api/oss'
import { mapGetters } from 'vuex'
export default {
  data () {
    return {
      showDialog: false,
      groupList: [],
      memberList: [],
      allList: [],
      waitAuthList: [], // 待审核商户列表
      current_page: 1,
      page_size: 20,
      order_by: 'SUM_VIEW',
      loading: false,
      total: 0,
      nextRoleType: '',
      oss_domain: '',
    }
  },
  computed: {
    ...mapGetters(['commonUrlPath']),
    role () {
      return sessionStorage.getItem('role')
    },
  },
  async mounted () {
    if (!sessionStorage.getItem('oss_domain')) {
      const res = await getOssDomain()
      sessionStorage.setItem('oss_domain', res.domain)
      this.oss_domain = res.domain
    } else {
      this.oss_domain = sessionStorage.getItem('oss_domain')
    }
    // 如果是总部账号 
    if (this.role === 'OPERATE') {
      selfTeamManage().then(res => {
        const { audit_list, pass_list } = res
        pass_list.forEach(i => {
          if (i.head_image) i.head_image = `${this.oss_domain}/${i.head_image}`
        })
        this.waitAuthList = audit_list
        this.memberList = pass_list
      })
    } else {
      if (this.role === 'HQ') {
        listMerchant({group_id: null}).then(res => {
          console.log('商户账号列表：', res)
          res.forEach(item => {
            if (item.head_image) item.head_image = `${this.oss_domain}/${item.head_image}`
          })
          this.allList = res
          this.getGroupList(res)
        })
        this.getListWaitAuthMerchant()
      } else {
        // 如果是商户的话，获取成员列表
        this.getAccountList()
        this.getListWaitAuthMember()
      }
    }
    document.title = '团队管理'
  },
  mounted () {
    this.nextRoleType = this.getNextRoleType()
    if (this.role === 'MERCHANT') {
      window.addEventListener('scroll', this.handleScroll,true) // 监听页面滚动*/
    }
  },
  methods: {
    getNextRoleType () {
      if (this.role === 'HQ') {
        return '新成员'
      }
      if (this.role === 'MERCHANT') {
        return '新成员'
      }
       if (this.role === 'OPERATE') {
        return '开通子账号'
      }
    },
    handleScroll () {
      console.log('this role:', this.role)
      if (this.loading) return
      const diff = 100
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      let scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
      //变量windowHeight是可视区的高度
      let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      //变量scrollHeight是滚动条的总高度
      let scrollHeight = document.documentElement.scrollHeight||document.body.scrollHeight;
      if (scrollHeight - scrollTop- windowHeight < diff && this.role !== 'HQ') {
        console.log('page teammanagegeneral - 到底部啦 role:', this.role)
        if (this.memberList.length < this.total) {
          this.current_page += 1
          this.getAccountList()
        }
      }
    },
    viewAccount (item) {
      this.$router.push({
        path: `${this.commonUrlPath}/accountdetail`,
        query: {
          account_id: item.id
        }
      })
    },
    getAccountList () {
      this.loading = true
      const { order_by, page_size, current_page} = this
      listMembers({
        merchant_id: sessionStorage.getItem('account_id'),
        current_page, order_by, page_size
      }).then(res => {
        console.log('查看素有成员：', res)
        res.list.forEach(item => {
          if (item.head_image) item.head_image = `${this.oss_domain}/${item.head_image}`
        })
        this.memberList = res.list
        this.total = res.total
        this.loading = false
      })
    },
    inviteMerchant () {
      this.showDialog = true
      inviteMerchant().then(res => {
        this.$nextTick(()=>{
          // 防止出现多个二维码
          if (document.querySelector('#qrcode > img')) {
            return
          }
          new QRCode('qrcode', {
            width: 800,  //宽度
            height: 800, // 高度  
            text: res, // 二维码内容--一般为后端传递过来的链接地址，当扫码二维码的时候，会进行相应的跳转 
            render: 'canvas' ,// 设置渲染方式（有两种方式 table和canvas，默认是canvas）  
          })
        })
      })
    },
    jumpDetail (item) {
      console.log('item:', item)
      const { username, mobile, id, remark, merchant_id } = item
      this.$router.push({
        path: `${this.commonUrlPath}/shopDetail`,
        query: {
          username, mobile, 
          merchant_id: id || merchant_id, 
          remark
        }
      })
    },
    // 获取待审核的商户
    getListWaitAuthMerchant () {
      listWaitAuthMerchant().then(res => {
        this.waitAuthList = res
      })
    },
    // 获取待审核的成员
    getListWaitAuthMember () {
      getWaitAuthMember().then(res => {
        this.waitAuthList = res
      })
    },
    getGroupList (list) {
      let arr = []
      list.forEach(item => {
        if (!arr.includes(item.group_name)) {
          arr.push(item.group_name)
        }
      })
      arr.forEach(name => {
        const group = {
          groupName: name,
          isFold: false,
          shopList: list.filter(i => i.group_name === name)
        }
        this.groupList.push(group)
      })
    },

    jump (path) {
      path = `${this.commonUrlPath}${path}`
      this.$router.push({ path })
    },
    jumpAuth (path, item) {
      path = `${this.commonUrlPath}${path}`
      const {id, username, mobile, remark } = item
      this.$router.push({ 
        path, 
        query: { 
          account_id: id, username, mobile, remark
        }
      })
    },
    toggleGroup (index) {
      const isFold = this.groupList[index].isFold
      this.$set(this.groupList[index], 'isFold', !isFold)
    }
  },
  beforeDestroy () {
    if (this.role === 'MERCHANT') {
      window.removeEventListener('scroll', this.handleScroll) // 监听页面滚动*/
    }
  }
}
</script>

<style scoped>
.yellow-text {
  color: #FF7628;
}
.view {
  font-family: Source Sans Pro;
  font-size: 3.73vw;
  font-weight: 600;
  color: #0A67FF;
}
::v-deep .van-popup {
  border-radius: 3.2vw;
}
::v-deep .van-overlay {
  background-color: rgba(0,0,0,.3);
}
.know-btn {
  width: 60.8vw;
  height: 8.53vw;
  line-height: 8.53vw;
  margin: 0 auto;
  text-align: center;
  border-radius: 1.1vw;
  background: #0A67FF;
  font-family: Source Han Sans CN;
  font-size: 3.2vw;
  font-weight: 500;
  color: #FFFFFF;
}
.qr {
  display: block;
  width: 56vw;
  height: 56vw;
  margin: 0 auto 10.13vw;
}
::v-deep #qrcode img {
  display: block;
  width: 100%;
  height: 100%;
}
::v-deep #qrcode canvas {
  display: block;
  width: 100%;
  height: 100%;
}
.dialog-sub-title {
  margin-bottom: 3.2vw;
  line-height: 4.53vw;
  font-family: Source Han Sans CN;
  font-size: 3.2vw;
  font-weight: 500;
  color: #333333;
}
.dialog-title {
  margin-bottom: 3.73vw;
  font-family: Source Han Sans CN;
  font-size: 3.73vw;
  font-weight: 500;
  text-align: center;
  color: #333333;
}

.popup-content {
  box-sizing: border-box;
  padding: 3.2vw 5.33vw;
}
.avatar-wrapper > img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.shop-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 89.6vw;
  height: 19.2vw;
  margin-bottom: 3.2vw;
  box-sizing: border-box;
  padding: 0 2.67vw 0 3.2vw;
  border-radius: 2.13vw;
  background: #FFFFFF;
  border: 0.27vw solid #E6E6E6;
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.06);
}
.shop-item-name {
  flex: 1;
}
.group-label-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 89.6vw;
  height: 10.67vw;
  background: #ffffff;
  box-sizing: border-box;
  padding: 0 3.2vw 0 3.73vw;
  border-radius: 2.13vw;
  margin-bottom: 5.33vw;
}
.group-label-cell > img {
  width: 4.27vw;
  height: 4.27vw;
}
.invite-btn {
  width: 19.47vw;
  height: 6.93vw;
  line-height: 6.93vw;
  text-align: center;
  border-radius: 1.07vw;
  background: #006EDD;
  font-family: Source Sans Pro;
  font-size: 3.2vw;
  font-weight: 600;
  color: #FFFFFF;
}
.green-text {
  font-family: Source Sans Pro;
  font-size: 3.73vw;
  font-weight: bold;
  color: #00A5A6;
}
.invite-cell {
  display: flex;
  height: 6.93vw;
  margin-bottom: 4.8vw;
  justify-content: space-between;
  align-items: center;
  font-family: Source Sans Pro;
  font-size: 3.73vw;
  font-weight: 600;
  color: #3D3D3D;
}
.auth-btn {
  width: 15.47vw;
  height: 7.47vw;
  line-height: 7.47vw;
  text-align: center;
  background: #FF7628;
  border-radius: 1.07vw;
  font-family: Source Sans Pro;
  font-size: 3.2vw;
  font-weight: 600;
  color: #FFFFFF;
}
.names {
  margin-bottom: 1.07vw;
}
.top-center {
  flex: 1;
}
.shop-name {
  font-family: Source Sans Pro;
  font-size: 3.2vw;
  font-weight: 600;
  line-height: 5.87vw;
  color: #999999;
}
.real-name {
  margin-right: 3.2vw;
  font-family: Source Han Sans CN;
  font-size: 3.73vw;
  font-weight: 500;
  line-height: 5.87vw;
  color: #3D3D3D;
}
.top-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  padding: 0 4vw 0 3.2vw;
  width: 89.6vw;
  height: 20.27vw;
  margin-bottom: 3.2vw;
  background: #FFFFFF;
  border-radius: 2.13vw;
  border: 0.27vw solid #E6E6E6;
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.06);
}
.avatar-wrapper {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 12.27vw;
  height: 12.27vw;
  border-radius: 50%;
  margin-right: 2.13vw;
  background: rgba(0, 0, 0, 0.28);
  overflow: hidden;
}
.avatar-text {
  font-family: Source Han Sans CN;
  font-size: 12px;
  font-weight: normal;
  letter-spacing: 0em;
  color: #FFFFFF;
}
.teams-manage {
  box-sizing: border-box;
  padding: 5.33vw 5.33vw 21.33vw;
}
.auth-title {
  margin-bottom: 3.2vw;
  font-family: Source Han Sans CN;
  font-size: 3.73vw;
  font-weight: 500;
  color: #FF7628;
}
.group-name {
  font-family: 思源黑体;
  font-size: 3.73vw;
  font-weight: 500;
  color: #999999;
}
</style>